package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        //width, height：图片的宽高，len：验证码的长度
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //获取验证码的值（验证码的校验在多数情况下不区分大小写，需要统一转成小写）
        String value = specCaptcha.text().toLowerCase();
        //可以根据key的前缀来判断键值对属于哪一个项目，哪一个功能模块
        //key的命名：不同的公司有不同的规范
        //项目名:功能模块名:其他
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();

        //将键值对保存到radius当中了，需要使用radiusTemplates
//        stringRedisTemplate：按照键值对的数据类型，对各种aip，各种方法进行分组，
        //String类型，opfValue组
        //timeout：时间长度：60
        //unit：时间单位：TimeUnit.SECONDS（秒）
        stringRedisTemplate.opsForValue().set(key, value, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //图片需要调用base64编码（转成String类型）
        CaptchaVo captchaVo = new CaptchaVo(specCaptcha.toBase64(), key);
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        if(loginVo.getCaptchaCode() == null){
            //因为有全局异常处理，直接抛出一个异常就可以
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //获取code：有可能为空，因为可能会过期
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(code == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //如果不为空需要将code 和 loginVo中的code进行比较，如果不相等，响应验证码错误
        //之前已经变成小写了，比较也要变成小写
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //校验用户状态密码
//        LambdaQueryWrapper<SystemUser> systemUserQueryUpdateWrapper = new LambdaQueryWrapper<>();
//        systemUserQueryUpdateWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        //只查询一条，只返回一条（不能这样写，因为之前设置的select = false导致查询不到）
//        SystemUser systemUser = systemUserMapper.selectOne(systemUserQueryUpdateWrapper);
        //手动写
        SystemUser systemUser = systemUserMapper.selectOneByUserName(loginVo.getUsername());

        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //校验状态
        //如果状态已禁用，给前端返回一个账号被禁的响应
        //BaseSstus：也是一个枚举类型
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //密码校验
        //给password增加了select = false，会导致空指针
        if (systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //为登录成功的用户创建JWT


        //创建一个Token返回给前端
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getLoginUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);

        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();

        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
